package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.comparator.CompareUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.redis.RedisCache;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.config.WebSocketServer;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.nursing.service.IAlertRuleService;
import com.zzyl.nursing.vo.AlertNotifyVo;
import com.zzyl.system.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 报警规则Service业务层处理
 *
 * @author ruoyi
 * @date 2025-01-17
 */
@Service
@Slf4j
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService {

    /**
     * 查询报警规则
     *
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id) {
        return getById(id);
    }

    /**
     * 查询报警规则列表
     *
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule) {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule) {
        return save(alertRule) ? 1 : 0;
    }

    /**
     * 修改报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule) {
        return updateById(alertRule) ? 1 : 0;
    }

    /**
     * 批量删除报警规则
     *
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除报警规则信息
     *
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private AlertRuleMapper alertRuleMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IAlertDataService alertDataService;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private WebSocketServer webSocketServer;

    @Value("${alert.deviceMaintainerRole}")
    private String deviceMaintainerRole;

    @Value("${alert.managerRole}")
    private String managerRole;
    /**
     * 设备数据报警
     */
    @Override
    public void deviceDataAlertJob() {
        //1，查询警规则是否存在
        long count = this.count(new LambdaQueryWrapper<AlertRule>().eq(AlertRule::getStatus, 1));
        if (count <= 0) {
            log.info("没有报警规则");
            return;
        }
        //2,查询所有设备最新上报的数据
        Map<String, Object> cacheMap = redisCache.getCacheMap(CacheConstants.IOT_DEVICE_LAST_DATA);
        if (CollUtil.isEmpty(cacheMap)) {
            log.info("没有设备数据");
            return;
        }

        cacheMap.forEach((iotId, value) -> {
            List<DeviceData> deviceDataList = JSONUtil.toList(value.toString(), DeviceData.class);
            deviceDataList.forEach(data -> {
                alertRuleData(data);
            });
        });
    }

    //数据匹配报警规则
    private void alertRuleData(DeviceData deviceData) {
        //1，获取所有关联设备规则
        List<AlertRule> alertRuleAll = this.list(new LambdaQueryWrapper<AlertRule>()
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getIotId, -1)
                .eq(AlertRule::getStatus, 1));

        //2，查询某个设备规则
        List<AlertRule> alertRuleIot = this.list(new LambdaQueryWrapper<AlertRule>()
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getIotId, deviceData.getIotId())
                .eq(AlertRule::getStatus, 1));

        //3,将所有设备数据满足的规则组合
        alertRuleAll.addAll(alertRuleIot);
        if (CollUtil.isEmpty(alertRuleAll)) {
            log.info("该设备没有满足的规则:"+deviceData.getDeviceName());
            return;
        }

        //4,用每条数据匹配规则
        alertRuleAll.forEach(alertRule -> {
            alertRuleMatchDeviceData(alertRule, deviceData);
        });
    }

    //每条数据匹配报警规则
    private void alertRuleMatchDeviceData(AlertRule alertRule, DeviceData deviceData) {
        //1，判断时间是否在生效时间内
        LocalTime localTime = deviceData.getAlarmTime().toLocalTime();
        String[] split = alertRule.getAlertEffectivePeriod().split("~");
        LocalTime startTime = LocalTime.parse(split[0]);
        LocalTime endTime = LocalTime.parse(split[1]);
        if (localTime.isBefore(startTime) || localTime.isAfter(endTime)) {
            log.info(deviceData.getDeviceName()+"设备的报警数据不在生效时间段内");
            return;
        }

        //2,校验数据是否达到阈值
        String silent = CacheConstants.IOT_SILENT_ALERT + ":" + deviceData.getIotId() + ":" + deviceData.getFunctionId() + ":" + alertRule.getId();
        String duration = CacheConstants.IOT_COUNT_ALERT + ":" + deviceData.getIotId() + ":" + deviceData.getFunctionId() + ":" + alertRule.getId();

        Double dataValue = Double.valueOf(deviceData.getDataValue());
        Double value = alertRule.getValue();
        //x>y 返回1，x=y返回0 x<y返回-1
        int compare = CompareUtil.compare(dataValue, value);
        if(">=".equals(alertRule.getOperator()) && compare >= 0 || "<".equals(alertRule.getOperator()) && compare < 0){
            log.info(deviceData.getDeviceName()+"设备数据满足报警条件，报警数据：{}", dataValue);

        }else{
            //删除redis报警数
            redisCache.deleteObject(duration);
        }

        //3，判断沉默周期
        Object cacheObject = redisCache.getCacheObject(silent);
        if (ObjectUtil.isNotEmpty(cacheObject)){
            log.info(deviceData.getDeviceName()+"的沉默周期未结束");
            return;
        }

        //4,判断持续周期
        Object count = redisCache.getCacheObject(duration);
        int sum = ObjectUtil.isEmpty(count) ? 1 : Integer.parseInt(count.toString())+1;
        if (sum != alertRule.getDuration()){
            log.info(deviceData.getDeviceName()+"设备的报警持续周期未到");
            redisCache.setCacheObject(duration, sum + "");
            return;
        }

        //5,所有规则满足
        redisCache.deleteObject(duration);

        //6,添加沉默周期
        redisCache.setCacheObject(silent, "有值",  alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);

        //7,校验完成
        List<Long> userIds = new ArrayList<>();
        if (alertRule.getAlertDataType().equals(0)){
            if (deviceData.getLocationType().equals(0)){
                //老人随身设备
                userIds = deviceMapper.selectNursingIdByIotIdWithElder(deviceData.getIotId());
                log.info(deviceData.getDeviceName()+"是老人随身设备");
            }else {
                //老人固定设备
                userIds = deviceMapper.selectNursingIdByIotIdWithBed(deviceData.getIotId());
                log.info(deviceData.getDeviceName()+"是老人固定设备");
            }
        }else {
            //房间设备
            userIds = userRoleMapper.selectByRoleName(deviceMaintainerRole);
            log.info(deviceData.getDeviceName()+"是房间设备");
        }
        List<Long> managers = userRoleMapper.selectByRoleName(managerRole);
        Collection<Long> list = CollUtil.addAll(userIds, managers);
        List<Long> allIds = CollUtil.distinct(list);

        //8,将报警数据插入数据库
        insertAlertData(allIds, alertRule, deviceData);


    }

    //将报警数据插入数据库,发送消息给前端
    private void insertAlertData(List<Long> allIds, AlertRule alertRule, DeviceData deviceData) {
        AlertData alertData = BeanUtil.toBean(deviceData, AlertData.class);
        alertData.setAlertRuleId(alertRule.getId());
        alertData.setAlertReason(alertRule.getFunctionName()+alertRule.getOperator()+alertRule.getValue()+",持续"+alertRule.getDuration()+"个周期报警");

        List<AlertData> list = allIds.stream().map(userId -> {
            AlertData dbAlertData = BeanUtil.toBean(alertData, AlertData.class);
            dbAlertData.setUserId(userId);
            dbAlertData.setAlertRuleId(alertRule.getId());
            dbAlertData.setStatus(0);
            dbAlertData.setId(null);
            dbAlertData.setType(alertRule.getAlertDataType());
            return dbAlertData;
        }).collect(Collectors.toList());
        alertDataService.saveBatch(list);
        log.info("添加报警数据成功：{}", list);

        //发送消息给前端
        AlertNotifyVo alertNotifyVo = BeanUtil.toBean(list.get(0), AlertNotifyVo.class);
        alertNotifyVo.setFunctionName(alertRule.getFunctionName());
        alertNotifyVo.setAlertDataType(alertRule.getAlertDataType());
        alertNotifyVo.setNotifyType(1);
        webSocketServer.sendMessageToConsumer(alertNotifyVo,  allIds);
    }
}
